<template>
  <div class="login">
    <Row
      type="flex"
      justify="center"
      align="middle"
      @keydown.enter.native="handleRegister"
      style="height:100%"
    >
      <Col class="layout" :span="18">
        <div>
          <div>
            <Row class="header">
              <img src="../../assets/images/logo.jpg" width="220px">
              <div class="description">iview admin前后端分离开发</div>
            </Row>
          </div>
          <Row>
            <Form
              ref="registerForm"
              :model="form"
              :rules="rules"
              class="form"
              label-position="left"
            >
              <span style=" display: block;font-weight: bold;font-size: 16px;margin-bottom: 2vh;">注册</span>
              <FormItem prop="username">
                <Input
                  v-model="form.username"
                  size="large"
                  clearable
                  placeholder="请输入用户名"
                  autocomplete="off"
                />
              </FormItem>
              <FormItem prop="password">
                <Input
                  v-model="form.password"
                  size="large"
                  type="password"
                  password
                  placeholder="请输入密码"
                  autocomplete="off"
                />
              </FormItem>
              <FormItem prop="confirmPassword">
                <Input
                  v-model="form.confirmPassword"
                  size="large"
                  type="password"
                  password
                  autocomplete="off" placeholder="请再次输入密码"/>
              </FormItem>
              <FormItem prop="phone">
                <Input
                  v-model="form.phone"
                  size="large"
                  placeholder="请输入手机号码"
                  autocomplete="off"
                />
              </FormItem>
              <FormItem prop="email">
                <Input
                  v-model="form.email"
                  size="large"
                  placeholder="请输入邮箱"
                  autocomplete="off"
                />
              </FormItem>
              <FormItem prop="gender">
                <Select v-model="form.gender"  clearable  placeholder="请选择性别">
                  <Avatar src="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar" slot="prefix" size="small" />
                  <Option :value="1">男</Option>
                  <Option :value="2">女</Option>
                </Select>
              </FormItem>
              <FormItem prop="birthday">
                <DatePicker type="date" format="yyyy-MM-dd" v-model="form.birthday" style="display: block" placeholder="请选择出生日期"></DatePicker>
              </FormItem>
              <FormItem prop="imgCode">
                <Row
                  type="flex"
                  justify="space-between"
                  style="align-items: center;overflow: hidden;"
                >
                  <Input
                    v-model="form.imgCode"
                    size="large"
                    clearable
                    placeholder="请输入图片验证码"
                    :maxlength="10"
                    class="input-verify"
                  />
                  <div class="code-image" style="position:relative;font-size:12px">
                    <img
                      :src="captchaImg"
                      @click="getCaptchaImg"
                      alt="加载验证码失败"
                      style="width:110px;cursor:pointer;display:block"
                    />
                  </div>
                </Row>
              </FormItem>
            </Form>
            <Row justify="space-between">
              <Button
                style="width: 40%"
                type="primary"
                size="large"
                :loading="loading"
                @click="handleRegister"
              >
                <span v-if="!loading">注册</span>
                <span v-else>提交中</span>
              </Button>
              <router-link to="/login">
                <a class="forget-pass" style="float: right;margin-top: 9px;">使用已有账户登录</a>
              </router-link>
            </Row>
          </Row>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import {checkUniqueness,registerUser} from "@/api/user";
import {timeFix} from "@/libs/tools";

export default {
  data(){
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不得小于6位'));
      } else {
        callback();
      }
    };
    const validateConfirmPass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不得小于6位'));
      } else if(this.form.password!=value) {
        callback(new Error("两次输入的密码不一致"));
      }else{
        callback()
      }
    };
    const validateUsername = (rule, value, callback) => {
      let reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,16}$/;
      if (value.length > 16) {
        callback(new Error('长度不能超过16个字符'));
      } else if (!reg.test(value)) {
        callback(new Error('仅支持大小写英文、中文和下划线_'));
      } else {
        checkUniqueness({value:value,oldValue:this.oldUsername}).then(res=>{
          if(res.data){
            callback(new Error("用户名已存在"));
          }else{
            callback();
          }
        })
      }
    };
    const validatePhone=(rule, value, callback)=>{
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error('手机号格式错误'));
      } else {
        checkUniqueness({value:value,oldValue:this.oldPhone}).then(res=>{
          if(res.data){
            callback(new Error("手机号码已存在"));
          }else{
            callback()
          }
        })
      }
    }
    const validateEmail=(rule, value, callback)=>{
      let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if(typeof(value)!='undefined'){
        if (!reg.test(value)) {
          callback(new Error('邮箱格式不正确'));
        } else {
          callback();
        }
      }else{
        callback()
      }
    }
    return{
      form:{
        t:null,
      },
      captchaImg:'',
      loading:false,
      rules:{
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {validator:validateUsername}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {validator:validatePass}
        ],
        confirmPassword:[
          {required: true, message: '请再次输入密码', trigger: 'blur' },
          {validator:validateConfirmPass}
        ],
        imgCode: [
          {
            required: true,
            message: "请输入图片验证码",
            trigger: "blur"
          }
        ],
        phone:[
          {required:true,message:'请输入手机号码',trigger:'blur'},
          {validator:validatePhone}
        ],
        email: [
          {required:true,message:'请输入邮箱',trigger:'blur'},
          {validator:validateEmail}
        ],
        gender:[
          {type:'number',required:true,message:'请选择性别',trigger:'change'}
        ],
        birthday:[
          {type:'date',required:true,message:'请选择出生日期',trigger:'change'}
        ]
      },
    }
  },
  methods: {
    handleRegister () {
      this.$refs.registerForm.validate(valid => {
        if(valid){
          this.loading = true
          registerUser(this.form)
            .then(res => {
              if (res.code == 200) {
                  this.$Message.success('注册成功');
                  setTimeout(() => {
                    this.$router.push({path:'/registerResult'})
                  }, 1000)
              } else {
                this.getCaptchaImg()
                this.loading = false
              }
            }).catch(()=>{
            this.getCaptchaImg()
            this.loading = false
          })
        }
      })
    },
    getCaptchaImg(){
      this.form.t = new Date().getTime()
      this.captchaImg='http://localhost:8020/code?t=' + this.form.t
    },
  },
  mounted(){
    this.getCaptchaImg();
  }
}
</script>


<style lang="less">
@import "./login.less";
.header {
  margin-top: 8vh;
  margin-bottom: 5vh;
  text-align: center;

  .description {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.45);
    margin-top: 1vh;
  }
}
</style>
